const { Op, literal } = require("sequelize");
const Message = require("../models/Message.js");
const User = require("../models/User.js");

class MessageService {
    async addMessage(messageData) {
        return Message.create(messageData);
    }
    async getMessageById(id) {
        return Message.findByPk(id);
    }
    async getAllMessages() {
        return Message.findAll();
    }
    async updateMessage(messageData) {
        const messageInstance = await Message.findByPk(messageData.id);
        messageInstance.update(messageData);
    }
    async deleteMessage(messageId) {
        return Message.destroy({
            where: {
                id: messageId
            }
        });
    }
    async getMessageListByPage(page = 1, limit = 10, keyword = undefined, sort = 'DESC') {
        let where = {
            deleted_at: null,
            [Op.or]: [
                {
                  content: {
                    [Op.like]: `%${keyword}%`,
                  },
                },
            ],
        }
        return Message.findAndCountAll({
            limit,
            offset: (page - 1) * limit,
            where,
            order: [['id', sort]],
            distinct: true,
            attributes: [
                'id',
                'content',
                [literal('DATE_FORMAT(Message.created_at, "%Y-%m-%d %H:%i:%s")'), 'created_at'],
                [literal('`user`.`email`'), 'email'],
            ],
            include: [
                {
                    model: User,
                    attributes: [],
                    as: 'user'
                }
            ]
        });
    }
}

module.exports = new MessageService();